package com.scott.java8concurrency.java8;

import java.time.LocalDate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * {@link CompletableFuture} demo1
 *
 * @see CompletionStage
 */
public class CompletableFutureDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //CompletableFuture<String> completableFuture = new CompletableFuture<>();

        //1：异步执行，但是是阻塞操作
//        CompletableFuture asyncCompletableFuture = CompletableFuture.runAsync(()->{
//            System.out.printf("Hello World");
//        }) ;
//
//        //仍然阻塞操作
//        asyncCompletableFuture.get();
//
//        System.out.printf("Staring....");

        //2:supplyAsync异步操作 阻塞操作
//        CompletableFuture<String> supplyAsyncCompletableFuture = CompletableFuture.supplyAsync(new Supplier<String>() {
//            @Override
//            public String get() {
//                //获取数据操作 假设来自于数据库
//                return String.format("[thread:%s] ", Thread.currentThread().getName());
//            }
//        });
//
//        System.out.printf("value = %s\n",supplyAsyncCompletableFuture.get());
//
//        System.out.printf("Staring....\n");

        //3:合并操作
        CompletableFuture combinedCompletableFuture =
                CompletableFuture.supplyAsync(() -> {
                    //获取数据操作 假设来自于数据库
                    return String.format("[thread:%s] hello World", Thread.currentThread().getName());
                })
                        .thenApply(value -> value + "-来自于数据库")
                        .thenApply(value -> value + LocalDate.now())
                        .thenApply(value -> {
                            System.out.println(value);
                            return value;
                        })
                        .thenRun(() -> {
                            System.out.println("操作结束");
                            //事务Commit操作
                        });


//        combinedCompletableFuture.get();

        while (!combinedCompletableFuture.isDone()) {

        }
        System.out.printf("Staring....\n");

    }
}
